import { defineStore } from 'pinia'
import {ref,computed} from 'vue'
export const useCounterStore = defineStore('counter', () => {
  //定义购物车列表
  const cartList=ref([])
  //购物车数量
  const totalCount=computed(()=>{
    let res=0
    cartList.value.forEach(item=>{
        res+=item.count
    })
    return res
  })
  //购物车价格
   const totalPrice=computed(()=>{
    let res=0
    cartList.value.forEach(item=>{
       if(item.checked)
       {
        res+=item.count*item.price
       }
    })
    return res.toFixed(2)*100
  })
  //加入购物车
  function addItem(payload){
    const index=cartList.value.findIndex(item=>item.id==payload.id)
    if(index>-1)
    {
        cartList.value[index].count++
    }
    else
    {
        cartList.value.push({
            ...payload,
            count:1,
            checked:false
        })
    }
  }
  //删除购物车
  function deleteItem(id){
    cartList.value=cartList.value.filter(item=>item.id!=id)
  }
  return {cartList,deleteItem,addItem,totalCount,totalPrice}
},{
  persist: true,
})